package com.RedRiver.hospitalsystem.finance_service.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import com.RedRiver.hospitalsystem.finance_service.client.param.TestTimeClient;
import com.RedRiver.hospitalsystem.finance_service.common.DateUtil;
import com.RedRiver.hospitalsystem.finance_service.common.Finance_serviceResultCode;
import com.RedRiver.hospitalsystem.finance_service.common.WebUtils;
import com.RedRiver.hospitalsystem.finance_service.common.WoniuxyBeanCopyUtil;
import com.RedRiver.hospitalsystem.finance_service.common.config.AlipayConfig;
import com.RedRiver.hospitalsystem.finance_service.common.exception.BillException;
import com.RedRiver.hospitalsystem.finance_service.infra.mapper.BillDetailMapper;
import com.RedRiver.hospitalsystem.finance_service.infra.mapper.BillMapper;
import com.RedRiver.hospitalsystem.finance_service.infra.model.Bill;
import com.RedRiver.hospitalsystem.finance_service.infra.model.BillDetail;
import com.RedRiver.hospitalsystem.finance_service.service.BillDetailService;
import com.RedRiver.hospitalsystem.finance_service.service.BillService;

import com.RedRiver.hospitalsystem.finance_service.service.from.*;
import com.RedRiver.hospitalsystem.finance_service.service.info.FindBillAllInfo;
import com.RedRiver.hospitalsystem.finance_service.service.info.FindBillAllListInfo;
import com.RedRiver.hospitalsystem.finance_service.service.info.FindBillDetailInfoXiList;
import com.RedRiver.hospitalsystem.finance_service.service.info.FindBillDetailXiInfo;
import com.RedRiver.hospitalsystem.medicine_service.client.MedicineClient;
import com.RedRiver.hospitalsystem.medicine_service.client.param.FindMedicineByIdInfoClient;
import com.RedRiver.hospitalsystem.pathology_service.client.CheckProjectClient;
import com.RedRiver.hospitalsystem.pathology_service.client.result.SearchCheckProjectResult;
import com.RedRiver.hospitalsystem.personal_service.client.ScheduleClient;
import com.RedRiver.hospitalsystem.personal_service.client.param.RegisterInformationForm;
import com.RedRiver.hospitalsystem.record_service.client.RecordsClient;
import com.RedRiver.hospitalsystem.record_service.client.SerialClient;
import com.RedRiver.hospitalsystem.record_service.client.result.GetTimeByIdResult;
import com.RedRiver.hospitalsystem.result.Result;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龙世超
 * @since 2022-04-26
 */
@Service
public class BillServiceImpl extends ServiceImpl<BillMapper, Bill> implements BillService {

    @Resource
    private BillMapper billMapper;
    @Resource
    private BillDetailMapper billDetailMapper;
    @Resource
    private SerialClient serialClient;
    @Resource
    private BillDetailService billDetailService;
    @Resource
    private ScheduleClient scheduleClient;
    @Resource
    private MedicineClient medicineClient;
    @Resource
    private CheckProjectClient checkProjectClient;

    //创建账单
    @Override
    public FindBillAllInfo createBill(CreateBillFrom copyone) {
        if (null==copyone.getWorkerId()||null==copyone.getCheckId()||null==copyone.getPaymentId())throw new BillException(50001,"请填写账单数据");
        Bill bill = WoniuxyBeanCopyUtil.copyone(copyone, Bill.class);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        long Temp; //不能设定为int,必须设定为long
        //产⽣10000000到20000000的随机数
        Temp=Math.round(Math.random()*10000000+20000000);
        String s =dateFormat.format(new Date())+Temp;
        bill.setBillNo(s);
        bill.setBillState(0);
        bill.setWorkerId(copyone.getWorkerId());
        bill.setMedicineState(0);
        int insert = billMapper.insert(bill);
        FindBillAllInfo info = WoniuxyBeanCopyUtil.copyone(bill, FindBillAllInfo.class);
        List<BillDetailFrom> list=new ArrayList<>();
        if (copyone.getList()!=null&&copyone.getList().size()!=0) {
             list= WoniuxyBeanCopyUtil.copyList(copyone.getList(),BillDetailFrom.class);
        }

        ArrayList<FindBillDetailXiInfo> findBillDetailXiInfos = new ArrayList<>();
        if (list!=null&&list.size()>0){
            for (BillDetailFrom from : list) {
                BillDetail detail = WoniuxyBeanCopyUtil.copyone(from, BillDetail.class);
                detail.setBillId(bill.getBillId());
                System.out.println("detail" + detail);

                System.out.println("+++++++++"+bill);



                billDetailMapper.insert(detail);
                FindBillDetailXiInfo copyone1 = WoniuxyBeanCopyUtil.copyone(detail, FindBillDetailXiInfo.class);
                if (bill.getPaymentId()==1){
                    Result<FindMedicineByIdInfoClient> medicineById = medicineClient.findMedicineById(detail.getTypeId());
                    if (medicineById.getCode()==200&&medicineById.getData()!=null) {
                        copyone1.setTypeName(medicineById.getData().getMedicineName());
                    }else throw new BillException(50001,"该药物id未找到任何数据");
                }
                else if (bill.getPaymentId()==2){
                    //查询检查项名，如上if
                    System.out.println(detail.getTypeId());
                    Result<SearchCheckProjectResult> result = checkProjectClient.searchCheckProjectById(detail.getTypeId());
                    System.out.println("result:" + result);
                    if (result.getCode()==200&&result.getData()!=null){
                        copyone1.setTypeName(result.getData().getCheckProjectName());
                    }else throw new BillException(50001,"该检查id未找到任何数据");
                }
                findBillDetailXiInfos.add(copyone1);
            }
        }
        info.setList(findBillDetailXiInfos);
        if (insert>0)return info;
        else throw new BillException(50001,"新建账单失败");
    }
    //分页查询所有账单
    @Override
    public FindBillAllListInfo findBillAll(FindBillAllForm copyone) {
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (copyone.getStart()!=null&&copyone.getStop()!=null){
            wrapper.between("create_time",copyone.getStart(),copyone.getStop());
        }
        Page<Bill> page = new Page<>(copyone.getCurrent(), copyone.getSize());
        IPage<Bill> page1 = page(page,wrapper);
        List<Bill> records = page1.getRecords();
        if (null==records||records.size()==0)throw new BillException(Finance_serviceResultCode.FIND_NOT_CODE);
        FindBillAllListInfo findBillAllListInfo = new FindBillAllListInfo();
        List<FindBillAllInfo> infoss = new ArrayList<>();
        for (Bill record : records) {
            FindBillAllInfo findBillAllInfo = WoniuxyBeanCopyUtil.copyone(record, FindBillAllInfo.class);
            if (record.getPaymentId()==1||record.getPaymentId()==2){
                FindBillDetailInfoXiList billDetailByIdXi = billDetailService.findBillDetailByIdXi(record.getBillId());
                if (billDetailByIdXi.getList()!=null&&billDetailByIdXi.getList().size()>0){
                    List<FindBillDetailXiInfo> infos = WoniuxyBeanCopyUtil.copyList(billDetailByIdXi.getList(), FindBillDetailXiInfo.class);
                    findBillAllInfo.setList(infos);
                }
            }
            infoss.add(findBillAllInfo);
        }
        List<FindBillAllInfo> infos = WoniuxyBeanCopyUtil.copyList(records, FindBillAllInfo.class);
        findBillAllListInfo.setList(infoss);
        findBillAllListInfo.setCurrent(page1.getCurrent());
        findBillAllListInfo.setSize(page1.getSize());
        findBillAllListInfo.setTotal(page1.getTotal());

        return findBillAllListInfo;
    }
    //账单支付
    @Override
    public String aliPay(Integer id) throws AlipayApiException {
        Bill bill = this.getById(id);
        if (bill == null) throw new BillException(50001,"该订单不存在");
        if(bill.getBillState()==1)throw new BillException(50001,"该订单已支付");
        //发送支付请求
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = bill.getBillNo();
        //付款金额，必填
        String total_amount =bill.getBillPrice().toString();
        //订单名称，必填
        String subject = bill.getPatientId()+"的订单";
        //商品描述，可空
        String body = "这是订单";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        return alipayClient.pageExecute(alipayRequest).getBody();
    }
    //同步通知
    @Override
    public FindBillAllInfo returnUrl() throws UnsupportedEncodingException {
        HttpServletRequest request = WebUtils.getRequest();
        HttpServletResponse response = WebUtils.getResponse();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (signVerified) {



        }else {
            System.out.println(123456789);
        }
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println(out_trade_no+"========================");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println(trade_no+"========================");
        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println(total_amount+"========================");
        Bill bill = billMapper.selectOne(new QueryWrapper<Bill>().eq("bill_no",out_trade_no));
        if (null==bill)throw new BillException(50001,"订单已不存在");
        return WoniuxyBeanCopyUtil.copyone(bill,FindBillAllInfo.class);

    }
    //异步通知
    @Override
    public void notyfyUrl() throws UnsupportedEncodingException {
        HttpServletResponse response = WebUtils.getResponse();
        HttpServletRequest request = WebUtils.getRequest();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(out_trade_no+"++++++++++++++++++++++");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(trade_no+"++++++++++++++++++++++");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(trade_status+"++++++++++++++++++++++");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(total_amount+"++++++++++++++++++++++");
            if (trade_status.equals("TRADE_FINISHED")) {

                System.out.println("TRADE_FINISHED");
            } else if (trade_status.equals("TRADE_SUCCESS")) {//支付完成
                System.out.println(total_amount+"-----------------------------");
                System.out.println(out_trade_no+"-----------------------------");
                System.out.println(trade_no+"-----------------------------");
                System.out.println(trade_status+"-----------------------------");
                //修改订单状态
                Bill bill = billMapper.selectOne(new QueryWrapper<Bill>().eq("bill_no",out_trade_no));
                if (null==bill)throw new BillException(50001,"订单已不存在");
                bill.setBillState(1);
                String time = DateUtil.parseDateLong(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
                LocalDateTime now = LocalDateTime.now();
                bill.setBillTime(now);
                bill.setPaymethodId(1);
                billMapper.updateById(bill);
            }

        } else {//验证失败
            System.out.println("11111111111122222222222233333333333");
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    //未支付取消订单
    @Override
    public Result<String> notOrder(Integer id) {
        Bill bill = billMapper.selectById(id);
        if (null==bill) throw new BillException(50001,"该订单不存在");
        if (bill.getBillState()==2)throw new BillException(50001,"该订单已退款");
        if (bill.getBillState()==1)throw new BillException(50001,"该订单已支付，请申请已支付退款");
        //删除账单
        billMapper.deleteById(bill);
        if (bill.getPaymentId()==1||bill.getPaymentId()==2){
            //删除账单详情
            QueryWrapper<BillDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("bill_id",bill.getBillId());
            List<BillDetail> billDetails = billDetailMapper.selectList(wrapper);
            if (billDetails!=null&&billDetails.size()>0){
                for (BillDetail billDetail : billDetails) {
                    billDetailMapper.deleteById(billDetail.getBillDetailId());
                }
            }
        }
        if (bill.getPaymentId()==3){
            //恢复号数为可挂号状态
            Result<GetTimeByIdResult> timeById = serialClient.getTimeById(bill.getCheckId());
            GetTimeByIdResult data = timeById.getData();
            if (data==null)throw new BillException(500001,"未获取到号的内容");
            RegisterInformationForm form = new RegisterInformationForm();
            form.setDate(data.getSerialDate());
            form.setDoctorId(data.getSerialId());
            scheduleClient.cancelRegisterInfomation(form);
        }
        return Result.getInstance(String.class).setData("取消订单成功").setCode(200);
    }
    //已支付取消订单
    @Override
    public Result<String> notYesOrder(Integer id) throws Exception {
        Bill bill = billMapper.selectById(id);
        if (null==bill) throw new BillException(50001,"该订单不存在");
        if (bill.getBillState()==2)throw new BillException(50001,"该订单已退款");
        if (bill.getBillState()==0)throw new BillException(50001,"该订单未支付");
        if (bill.getMedicineState()==1)throw new BillException(50001,"该订单已消费");
        if (bill.getPaymethodId()==1) {
            //调用退款接口
            RefundFrom refundForm = new RefundFrom();
            refundForm.setId(bill.getBillId());
            HttpServletRequest request = WebUtils.getRequest();
            HttpServletResponse response = WebUtils.getResponse();
            System.out.println("================");
            toRefund(refundForm, request, response);
        }
        //修改订单状态
        LocalDateTime now = LocalDateTime.now();
        bill.setRefundTime(now);
        bill.setBillState(2);
        billMapper.updateById(bill);
        if (bill.getPaymentId()==3){
            //恢复号数为可挂号状态
            Result<GetTimeByIdResult> timeById = serialClient.getTimeById(bill.getCheckId());
            GetTimeByIdResult data = timeById.getData();
            RegisterInformationForm form = new RegisterInformationForm();
            form.setDate(data.getSerialDate());
            form.setDoctorId(data.getSerialId());
            scheduleClient.cancelRegisterInfomation(form);
        }
        return Result.getInstance(String.class).setData("取消订单成功，已退款").setCode(200);
    }
    //退款
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String toRefund(RefundFrom refundFrom, HttpServletRequest request, HttpServletResponse response)throws Exception {
        Bill bill = billMapper.selectById(refundFrom.getId());
        if (bill==null) {
            throw new BillException(50001,"不存在该订单退款失败");
        }
        if (bill.getBillState().equals("0")) {
            throw new BillException(50001,"该订单未付款");
        }
        if (bill.getBillState().equals("2")) {
            throw new BillException(50001,"该订单已取消");
        }
        if (bill.getMedicineState()==1) {
            throw new BillException(50001,"该订单已消费");
        }
        // 设置编码格式
        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，必填
        String out_trade_no = bill.getBillNo();
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = bill.getBillPrice().toString();
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(UUID.randomUUID().toString());
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        //请求
        AlipayTradeRefundResponse resp = alipayClient.execute(alipayRequest);
        //以下写自己的订单退款代码
        if(resp.isSuccess()){
            System.out.println("支付宝退款成功");
            Result<?> result = Result.getInstance().setMsg("退款成功");
//            response.getWriter().write(new JSONObject().toJSONString(result));
        } else {
            System.out.println("退款失败");
//            response.getWriter().write(new JSONObject().toJSONString("调用失败"));
            response.getWriter().write(resp.getBody());
        }

        return "退款成功";
    }

    @Override
    public Bill changeBillById(ChangeBillByIdFrom byIdFrom) {
        Bill bill = WoniuxyBeanCopyUtil.copyone(byIdFrom, Bill.class);
        billMapper.updateById(WoniuxyBeanCopyUtil.copyone(byIdFrom, Bill.class));
        return bill;
    }

    @Override
    public FindBillAllInfo findBillByCheckId(Integer id) {
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.eq("check_id",id);
        Bill bill = baseMapper.selectOne(wrapper);
        if (bill!=null){
            return WoniuxyBeanCopyUtil.copyone(bill,FindBillAllInfo.class);
        }throw new BillException(500,"未找到账单");
    }

    @Override
    public String moniYibao(Integer id) {
        Bill bill = this.getById(id);
        if (bill == null) throw new BillException(50001,"该订单不存在");
        if(bill.getBillState()==1)throw new BillException(50001,"该订单已支付");
        //修改订单状态
        bill.setBillState(1);
        String time = DateUtil.parseDateLong(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        bill.setBillTime(now);
        bill.setPaymethodId(2);
        billMapper.updateById(bill);
        return "医保卡支付成功";
    }

    @Override
    public FindBillAllInfo getOneById(Integer id) {
        Bill bill = billMapper.selectById(id);
        if (bill==null)throw new BillException(50001,"未找到该订单");
        FindBillAllInfo copyone = WoniuxyBeanCopyUtil.copyone(bill, FindBillAllInfo.class);
        if (copyone.getPaymentId()==1||copyone.getPaymentId()==2){
            FindBillDetailInfoXiList billDetailByIdXi = billDetailService.findBillDetailByIdXi(id);
            System.out.println(billDetailByIdXi);
            if (billDetailByIdXi.getList()!=null&&billDetailByIdXi.getList().size()>0){
                List<FindBillDetailXiInfo> infos = WoniuxyBeanCopyUtil.copyList(billDetailByIdXi.getList(), FindBillDetailXiInfo.class);
                copyone.setList(infos);
            }
        }
        return copyone;
    }


}
